#ifndef __MY__TCP__
#define __MY__TCP__

#include <cstdlib>
#include <cstring>
// #include <mutex>
#include <pthread.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

#define BACKLOG 5

class TcpServer
{
private:
    int _port;
    int _listen_sock;
    static TcpServer *svr; // 单例模式，静态成员变量，需要在类外初始化
    static pthread_mutex_t lock;

private:
    TcpServer(int port) : _port(port), _listen_sock(-1) {
        // std::cout<<_port<<" : _port"<<std::endl;    8888
    }
    TcpServer(const TcpServer &s) {}

public:
    static TcpServer *GetInstance(int port)
    {
        if (svr == nullptr)
        {
            pthread_mutex_lock(&lock);
            if (svr == nullptr)
            {
                svr = new TcpServer(port);
                svr->InitServer();
            }
            pthread_mutex_unlock(&lock);
        }
        return svr;
    }

    void InitServer()
    {
        Socket();
        Bind();
        Listen();

        LOG(INFO, "tcp_sever init successs!");
    }

    void Socket()
    {
        _listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sock < 0)
        {
            LOG(FATAL, "socket error !");
            exit(1);
        }
        int opt = 1;
        setsockopt(_listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt); // 设置端口号复用

        LOG(INFO, "create socket success !");
    }
    void Bind()
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);       // 主机序-》netshort  网络序短整型
        // std::cout<<"local.sin_port"<<local.sin_port<<std::endl;
        local.sin_addr.s_addr = INADDR_ANY; // 云服务器不能直接绑定公网IP， 因为公网IP是运营商虚拟给我们的，找不到
                                            // 要绑定自己的IP
        if (bind(_listen_sock, (struct sockaddr *)&local, sizeof local) < 0){
            LOG(FATAL, "bind error !");
            exit(2);
        }
        LOG(INFO, "bind success !");
    }

    void Listen()
    {
        if (listen(_listen_sock, BACKLOG) < 0){
            LOG(FATAL, "listen error !");
            exit(3);
        }
        LOG(INFO, "listen socket success !");
    }


    int Sock()
    {
        return _listen_sock;
    }

    ~TcpServer() {
        if(_listen_sock>=0)
            close(_listen_sock);
    }
};
TcpServer *TcpServer::svr = nullptr;
pthread_mutex_t TcpServer::lock = PTHREAD_MUTEX_INITIALIZER; // 需要在类外初始化
#endif
